from fastapi import APIRouter, Query, UploadFile, BackgroundTasks
from tortoise.expressions import Q

from app.controllers.customer.users import users_controller
from app.controllers.exams.exam import exam_controller
from app.controllers.exams.question import question_controller
from app.controllers.exams.user_answer import user_answer_controller
from app.controllers.system.user import user_controller
from app.models import Question, Result, UserAnswer
from app.schemas.base import Success, SuccessExtra, Fail
from app.core.dependency import DependCustomerAuth
from app.core.ctx import CTX_USER_ID
from app.schemas.exams import UserAnswerCreate, UserAnswerPost

exam_router = APIRouter()
model_name = "问卷"


@exam_router.get("/list", summary=f"查看{model_name}列表")
async def do_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        title: str = Query(None, description=f"名称"),
):
    q = Q()
    if title:
        q &= Q(title__contains=title)
    total, data = await exam_controller.do_list(page=page, page_size=page_size, search=q)
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)


@exam_router.get("/get", summary=f"查看{model_name}题目")
async def do_get(
        data_id: int = Query(0, description="ID"),
):
    data = await question_controller.do_detail(data_id=data_id)
    return Success(data=data)


@exam_router.post("/get_answer", summary=f"提交答案", dependencies=[DependCustomerAuth])
async def do_get_answer(
        answer_data: UserAnswerPost,
):
    user_id = CTX_USER_ID.get()
    print(user_id,231)
    answer_data.user_id = user_id
    await users_controller.update_last_login(user_id)
    user_score = 0
    answer = answer_data.user_answer
    for item in answer:
        question = await Question.filter(id=item["question_id"]).first().values("answer")
        for v1 in question["answer"]:  ##是:1 否0
            question_data = v1.split("|")
            select_data = item["select"].split("|")
            if question_data[0] == select_data[0]:
                user_score += int(question_data[1])

    if answer_data.exam_id == 40:
        if user_score < 7:
            result = {
                "exam_id": 41
            }
            return Success(data=result)

    result_data = await Result.filter(exam_id=answer_data.exam_id, score_max__gte=user_score,
                                      score_min__lte=user_score).first().values("picture", "name", "rate")
    obj_in = UserAnswerCreate(
        user_id=answer_data.user_id,
        exam_id=answer_data.exam_id,
        user_answer=answer_data.user_answer,
        user_score=user_score,
        result_name=result_data['name']
    )

    ret = await user_answer_controller.do_create(obj_in=obj_in)
    if ret:
        return Success(data=result_data)
    else:
        return Fail(msg="生成失败")


@exam_router.post("/get_answer1", summary=f"新提交答案", dependencies=[DependCustomerAuth])
async def do_get_answer1(
        answer_data: UserAnswerPost,
):
    user_id = CTX_USER_ID.get()
    await users_controller.update_last_login(user_id)
    await UserAnswer.filter(user_id=user_id,exam_id=answer_data.exam_id).delete()
    obj_in = UserAnswerCreate(
        user_id=user_id, exam_id=answer_data.exam_id, user_answer=answer_data.user_answer,
    )

    ret = await user_answer_controller.do_create(obj_in=obj_in)

    if ret:
        return Success(msg="提交成功")
    else:
        return Fail(msg="提交失败")

@exam_router.get("/answer_list", summary=f"查看头皮档案",dependencies=[DependCustomerAuth])
async def do_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        exam_id: int = Query(0, description=f"问卷id"),
        customer_id = Query(0, description="用户id"),
):
    q = Q()
    user_id = CTX_USER_ID.get()
    if customer_id:
        user_id = customer_id
    q &= Q(user_id=user_id)
    if exam_id:
        q &= Q(exam_id=exam_id)
    total, data = await user_answer_controller.do_list(page=page, page_size=page_size, search=q)

    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)